//
//  SearchBlueViewController.m
//  LazyCat
//
//  Created by jike on 15/12/17.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "SearchBlueViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "MSBluetoothManager.h"
#import "FeWifiManHub.h"

#import "HLBLEManager.h"

@interface SearchBlueViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    FeWifiManHub *_loading;

}
@property (nonatomic, retain) UITableView *tableView;
//@property (nonatomic, retain) NSMutableArray *countArr;
/** 辅助的tableView,用来获取chatacter的值  */
@property(nonatomic,strong)UITableView *assistTableView;
/** 蓝牙设备数组  */
@property(nonatomic,strong)NSMutableArray *bleDeviceArrs;

@property (nonatomic,strong)CBPeripheral *perpheral;

/** 某个蓝牙的服务数组  */
@property(nonatomic,strong)NSMutableArray *serviceArrs;

@property (strong, nonatomic)CBCharacteristic *chatacter;  /**< 可写入数据的特性 */
@end

@implementation SearchBlueViewController

-(NSMutableArray *)bleDeviceArrs
{
    if (_bleDeviceArrs == nil) {
        _bleDeviceArrs = [NSMutableArray array];
    }
    return _bleDeviceArrs;
}

-(NSMutableArray *)serviceArrs
{
    if (_serviceArrs == nil) {
        _serviceArrs = [NSMutableArray array];
    }
    return _serviceArrs;
}
//-(void)viewWillAppear:(BOOL)animated {
//    NSString *swit = [ NSUserDefualManager getValueByKey:@"switch"];
//    if ([swit isEqualToString:@"on"]) {
//        [[MSBluetoothManager shareInstance] startScan];
//        [_loading removeFromSuperview];
//        _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
//        [self.view addSubview:_loading];
//        [_loading show];
//        [self  performSelector:@selector(getVersionMessg) withObject:nil afterDelay:10];
//    }
//}
//-(void)notice {
//    self.countArr = [MSBluetoothManager shareInstance].nDevices;
//    if (self.countArr.count > 0) {
//        [_loading dismiss];
//    }
//    [self.tableView reloadData];
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNav:@"搜索打印机" doBack:YES];
    UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, 1)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    lineV.alpha = 0.2;
    [self.view addSubview:lineV];
    
    [self createTable];
    
   
}

-(void)createTable {
  
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 74, ScreenWidth, 50)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    UISwitch *swit = [[UISwitch alloc] initWithFrame:CGRectMake(ScreenWidth - 60, 10, 60, 20)];
    swit.onTintColor=  MainColor;
    NSString *cid = [ NSUserDefualManager getValueByKey:@"switch"];
    if ([cid isEqualToString:@"on"]) {
        swit.on = YES;
        [self scanBLEDevices];
    }else{
        swit.on = NO;
    }
    [swit addTarget:self action:@selector(switchClicked:) forControlEvents:UIControlEventValueChanged];
    [topView addSubview:swit];
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, 150, 20)];
    lable.font = FontSet(15);
    lable.text = @"蓝牙打印";
    [topView addSubview:lable];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 134, ScreenWidth, ScreenHeight - 134) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
 
    
}

-(void)switchClicked:(UISwitch *)sw
{
    if (sw.on) {
        [self scanBLEDevices];
        NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults]; // 蓝牙开关
        [userDefaul setObject:@"on" forKey:@"switch"];
    }else{
        NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults]; // 蓝牙开关
        [userDefaul setObject:@"off" forKey:@"switch"];
        [self.bleDeviceArrs removeAllObjects];
        [self.serviceArrs removeAllObjects];
        [AppData share].chatacter = nil;
        self.perpheral = nil;
        [self.tableView reloadData];
        [self.assistTableView reloadData];
        HLBLEManager *manager = [HLBLEManager sharedInstance];
        [manager stopScan];
        [manager cancelPeripheralConnection];
        
    }
}


#pragma mark --- 扫描周边蓝牙设备
-(void)scanBLEDevices
{
    HLBLEManager *manager = [HLBLEManager sharedInstance];
    __weak HLBLEManager *weakManager = manager;
    manager.stateUpdateBlock = ^(CBCentralManager *central) {
        NSString *info = nil;
        switch (central.state) {
            case CBCentralManagerStatePoweredOn:
                info = @"蓝牙已打开，并且可用";
                //三种种方式
                // 方式1
                [weakManager scanForPeripheralsWithServiceUUIDs:nil options:nil];
                //                // 方式2
                //                [central scanForPeripheralsWithServices:nil options:nil];
                //                // 方式3
                //                [weakManager scanForPeripheralsWithServiceUUIDs:nil options:nil didDiscoverPeripheral:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
                //
                //                }];
                break;
            case CBCentralManagerStatePoweredOff:
                info = @"蓝牙可用，未打开";
                break;
            case CBCentralManagerStateUnsupported:
                info = @"SDK不支持";
                break;
            case CBCentralManagerStateUnauthorized:
                info = @"程序未授权";
                break;
            case CBCentralManagerStateResetting:
                info = @"CBCentralManagerStateResetting";
                break;
            case CBCentralManagerStateUnknown:
                info = @"CBCentralManagerStateUnknown";
                break;
        }
 
        [[MessShowView share]showWithMess:info];
    };
    
    manager.discoverPeripheralBlcok = ^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        if (peripheral.name.length <= 0) {
            return ;
        }
        
        if (self.bleDeviceArrs.count == 0) {
            NSDictionary *dict = @{@"peripheral":peripheral, @"RSSI":RSSI};
            [self.bleDeviceArrs addObject:dict];
        } else {
            BOOL isExist = NO;
            for (int i = 0; i < self.bleDeviceArrs.count; i++) {
                NSDictionary *dict = [self.bleDeviceArrs objectAtIndex:i];
                CBPeripheral *per = dict[@"peripheral"];
                if ([per.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
                    isExist = YES;
                    NSDictionary *dict = @{@"peripheral":peripheral, @"RSSI":RSSI};
                    [self.bleDeviceArrs replaceObjectAtIndex:i withObject:dict];
                }
            }
            
            if (!isExist) {
                NSDictionary *dict = @{@"peripheral":peripheral, @"RSSI":RSSI};
                [self.bleDeviceArrs addObject:dict];
            }
        }
        
        [self.tableView reloadData];
        
    };
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.assistTableView) {
        return self.serviceArrs.count;
    }else{
        return 1;
    }
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        return self.bleDeviceArrs.count;
    }else{
        CBService *service ;
        if (self.serviceArrs.count > section) {
           service = [self.serviceArrs objectAtIndex:section];
        }
        return [service.characteristics count];

    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.tableView) {
        return 60;
    }
    return 100;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (tableView == self.tableView) {
        static NSString *identifier = @"deviceId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        }
        
        NSDictionary *dict = [self.bleDeviceArrs objectAtIndex:indexPath.row];
        CBPeripheral *peripherral = dict[@"peripheral"];
        cell.textLabel.text = [NSString stringWithFormat:@"名称:%@",peripherral.name];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"信号强度:%@",dict[@"RSSI"]];
        if (peripherral.state == CBPeripheralStateConnected) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        return cell;
        

    }else{
        static NSString *identifier = @"infoCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            
        }
        
        CBService *service ;
        if (self.serviceArrs.count > indexPath.section) {
            service = self.serviceArrs[indexPath.section];
        }
        CBCharacteristic *character = [service.characteristics objectAtIndex:indexPath.row];
        CBCharacteristicProperties properties = character.properties;
        /**
         CBCharacteristicPropertyWrite和CBCharacteristicPropertyWriteWithoutResponse类型的特性都可以写入数据
         但是后者写入完成后，不会回调写入完成的代理方法{peripheral:didWriteValueForCharacteristic:error:},
         因此，你也不会受到block回调。
         所以首先考虑使用CBCharacteristicPropertyWrite的特性写入数据，如果没有这种特性，再考虑使用后者写入吧。
         */
        //
        if (properties & CBCharacteristicPropertyWrite) {
            //        if (self.chatacter == nil) {
            //            self.chatacter = character;
            //        }
            self.chatacter = character;
            [AppData share].chatacter = character;
        }
        cell.textLabel.text = [NSString stringWithFormat:@"%@",character.description];
        cell.textLabel.numberOfLines = 0;
        return cell;
  
    }
  
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dict = [self.bleDeviceArrs objectAtIndex:indexPath.row];
    self.perpheral = dict[@"peripheral"];
    
    
    [self creatAssistTableview];
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (cell.selected) {  //已经选中了某个蓝牙
        
    }else{ //选择别的蓝牙
        HLBLEManager *manager = [HLBLEManager sharedInstance];
        [manager cancelPeripheralConnection]; //断开之前的连接
        [self.serviceArrs removeAllObjects];
        [self.assistTableView reloadData];
    }
    [self loadBLEInfo:tableView indexPath:indexPath];
    
 

}
-(void)creatAssistTableview
{
    self.assistTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, ScreenHeight+10, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    self.assistTableView.delegate = self;
    self.assistTableView.dataSource = self;
    [self.view addSubview:self.assistTableView];
}

- (void)loadBLEInfo:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    __weak typeof(cell) weakCell = cell;
    HLBLEManager *manager = [HLBLEManager sharedInstance];
    [manager connectPeripheral:_perpheral
                connectOptions:@{CBConnectPeripheralOptionNotifyOnDisconnectionKey:@(YES)}
        stopScanAfterConnected:YES
               servicesOptions:nil
        characteristicsOptions:nil
                 completeBlock:^(HLOptionStage stage, CBPeripheral *peripheral, CBService *service, CBCharacteristic *character, NSError *error) {
                     switch (stage) {
                         case HLOptionStageConnection:
                         {
                             if (error) {
                                 [[MessShowView share]showWithMess:@"连接失败"];
                             } else {
                                 
                             }
                             break;
                         }
                         case HLOptionStageSeekServices:
                         {
                             if (error) {
                                 [[MessShowView share]showWithMess:@"连接失败"];
//                                 [SVProgressHUD showSuccessWithStatus:@"查找服务失败"];
                             } else {
//                                 [SVProgressHUD showSuccessWithStatus:@"查找服务成功"];
                                   [_serviceArrs addObjectsFromArray:peripheral.services];
                                   [self.assistTableView reloadData];
                             }
                             break;
                         }
                         case HLOptionStageSeekCharacteristics:
                         {
                             // 该block会返回多次，每一个服务返回一次
                             if (error) {
//                                 [SVProgressHUD showErrorWithStatus:@"连接失败"];
                                 [[MessShowView share]showWithMess:@"连接失败"];
                             } else {
                                 [self.assistTableView reloadData];
                             }
                             break;
                         }
                         case HLOptionStageSeekdescriptors:
                         {
                             // 该block会返回多次，每一个特性返回一次
                             if (error) {
                                 [[MessShowView share]showWithMess:@"连接失败"];
//                                 NSLog(@"查找特性的描述失败");
                             } else {
                                 // NSLog(@"查找特性的描述成功");
                                 [[MessShowView share]showWithMess:@"连接成功"];
                                 weakCell.accessoryType = UITableViewCellAccessoryCheckmark;
                                 weakCell.selected = YES;
                                 [self.tableView reloadData];

                             }
                             break;
                         }
                         default:
                             break;
                     }
                     
                 }];
}

@end
